const app = getApp();
import { get, post } from '../../../utils/request';
import auth from '../../../utils/auth';

Page({
  data: {
    userInfo: null,
    loading: false,
    username: '',
    email: '',
    phone: '',
    avatar: '',
    avatarFiles: []
  },

  onLoad() {
    this.getUserInfo();
  },

  // 获取用户信息
  getUserInfo() {
    this.setData({ loading: true });

    get('/api/user/get/login')
      .then(res => {
        if (res.code === 0 && res.data) {
          const userInfo = {
            id: res.data.id,
            username: res.data.username,
            email: res.data.email || '',
            phone: res.data.phone || '',
            avatar: res.data.avatar || '/assets/images/icons/default-avatar.png'
          };

          this.setData({
            userInfo: userInfo,
            username: userInfo.username,
            email: userInfo.email,
            phone: userInfo.phone,
            avatar: userInfo.avatar,
            loading: false
          });

          // 如果有头像，设置到avatarFiles中
          if (userInfo.avatar && userInfo.avatar !== '/assets/images/icons/default-avatar.png') {
            this.setData({
              avatarFiles: [{
                url: userInfo.avatar,
                uploadTime: new Date().getTime(),
                index: 0
              }]
            });
          }
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('获取用户信息失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 处理头像上传变更
  handleAvatarChange(e) {
    const { files } = e.detail;

    this.setData({
      avatarFiles: files,
      avatar: files.length > 0 ? files[0].url : ''
    });
  },

  // 处理输入框变更
  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;

    this.setData({
      [field]: value
    });
  },

  // 提交表单
  submitForm() {
    const { username, email, phone, avatar } = this.data;

    // 校验头像
    if (!avatar || avatar === '/assets/images/icons/default-avatar.png') {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      });
      return;
    }

    // 校验手机号
    if (!phone) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none'
      });
      return;
    }

    // 校验手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return;
    }

    // 显示加载提示
    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    // 调用更新用户信息接口
    wx.request({
      url: `${app.globalData.baseUrl}/api/user/update/my`,
      method: 'POST',
      header: {
        'Authorization': app.globalData.token
      },
      data: {
        nickname: username,
        phone: phone,
        avatarUrl: avatar
      },
      success: (res) => {
        if (res.data.code === 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });

          // 更新本地存储的用户信息
          const userInfo = {
            ...this.data.userInfo,
            nickname: username,
            phone: phone,
            avatarUrl: avatar
          };
          wx.setStorageSync('userInfo', userInfo);

          // 返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.msg || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 跳回上一页
  goBack() {
    wx.navigateBack();
  }
}) 